<?php

require_once('resource.php');

// This class represents a artifact item.
//      It is based on the artifact class.
class folio_artifact extends folio_resource {

    // This differs from the ID value in the base class, as it represnts the ident
    //      number for the saved artifact in the db.
    public $artifact_ident = -1;
    public $reflection = '';
    public $newest = 1;

    // Location of the artifact, user & page IDs.
    public $page_owner;
    public $page_ident;

    // Constructor
    function folio_artifact( $array ) {
        // Assume constructor is an array from the db.

        foreach ( $array as $n=>$v ) {
            $this->$n = $v; //( $r . ' = ' . $v . '<br/>' );
        }
    }

    function handle() {
        return 'folio_artifact' . $this->artifact_ident;
    }

//////////////////
//              //
//  SQL Layer   //
//              //
//////////////////

    /**
     * Return all artifacts for the page.
     * @param int $page_ident The page for which we're retrieving records
     * @param int $newest Optional, what is the status of the artifacts we want?
     * @return array with a each matching item.
     */
    function SelectWherePageIdent( $page_ident, $newest = 1 ) {
        global $CFG;
        $artifacts = array();

        $query = "SELECT a.artifact_ident, a.* FROM {$CFG->prefix}folio_artifact a " .
                    "WHERE a.page_ident = $page_ident AND newest = $newest";

        $records = recordset_to_array( get_recordset_sql( $query ));

        if( !$records ) {return $artifacts; }

        foreach( $records as $record ) {
            $artifacts[$record->artifact_ident] = new folio_artifact( $record );
        }

        return $artifacts;
    }

    /**
     * Return an artifact
     * @param int $decoration_ident
     * @param int $newest Optional, what is the status we want?
     * @return folio_decoration
     */
    function SelectWhereArtifactIdent( $artifact_ident, $newest = 1 ) {
        global $CFG;

        $query = "SELECT a.artifact_ident, a.* FROM {$CFG->prefix}" .
                    "folio_artifact a WHERE a.artifact_ident = " .
                    $artifact_ident . ' AND newest = ' . $newest;

        $a = recordset_to_array( get_recordset_sql( $query ));

        return new folio_artifact( $a[$artifact_ident] );
    }

    /**
     * This will load resources into artifacts in the db, and return new objects
     *
     * @param array $resources Array of resources
     * @param ident $page_owner
     * @param ident $page_ident
     * @return array Array of new artifacts
     */
    function CreateArtifactsFromResources( $resources, $page_owner, $page_ident ) {
        global $CFG;
        $artifacts = array();

        foreach ( $resources as $r ) {
           // Create a new record with the correct vars

            $i = new StdClass();
            $i->page_ident = $page_ident;
            $i->page_owner = $page_owner;
            $i->newest = 1;
            foreach( $r as $n=>$v ){
                $i->$n=$v;
            }

            $artifact_ident = insert_record( 'folio_artifact', $i );
            // Load the new artifact from the db for the constructor.

            $a = folio_artifact::SelectWhereArtifactIdent( $artifact_ident );

            $artifacts[] = $a;
        }

        return $artifacts;
    }

    /**
     * Update an artifact in the db.
     *
     * @param folio_artifact $artifact
     * @return folio_artifact Updated record
     */
    function Update( folio_artifact $artifact ) {
        return ( folio_artifact::local_update_record( 'folio_artifact',
                $artifact, 'artifact_ident' ) );
    }

    /**
     * Called to delete the record from the db
     *
     * Changes status to 0 so that it no longer shows up.
     *
     * @param int $artifact_ident
     * @return boolean Success
     */
    function Delete( $artifact_ident ) {
        $a = folio_artifact::SelectWhereArtifactIdent( $artifact_ident );
        $a->newest = 0;
        folio_artifact::Update($a);
        return true;
    }

    // This is a modification of update_record in datalib.php that is
    //      able to accept alternative ident column names.
    private function local_update_record($table, $dataobject, $ident) {
        global $db, $CFG;

        static $table_columns;

        // Determine all the fields in the table
        if (is_array($table_columns) && array_key_exists($table,$table_columns)) {
            $columns = $table_columns[$table];
        } else {
            if (!$columns = $db->MetaColumns($CFG->prefix . $table)) {
                return false;
            }
            $table_columns[$table] = $columns;
        }

        $data = (array)$dataobject;
        $ddd = array();

        if (defined('ELGG_PERFDB')) { global $PERF ; $PERF->dbqueries++; };

        // Pull out data matching these fields
        foreach ($columns as $column) {
            if ($column->name <> $ident and isset($data[$column->name]) ) {
                $ddd[$column->name] = $data[$column->name];
            }
        }

        // Construct SQL queries
        $numddd = count($ddd);
        $count = 0;
        $update = '';

        foreach ($ddd as $key => $value) {
            $count++;
            $update .= $key .' = ?';
            if ($count < $numddd) {
                $update .= ', ';
            }
        }

//return( 'UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE ' . $ident . ' = \''. $dataobject->$ident .'\'' );
        $stmt = $db->Prepare('UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE ' . $ident . ' = \''. $dataobject->$ident .'\'');
        if ($rs = $db->Execute($stmt,$ddd)) {
            elggcache_delete($table, "{$ident}_" . $dataobject->$ident);
            return true;
        } else {
            if (isset($CFG->debug) and $CFG->debug > 7) {
                notify($db->ErrorMsg() .'<br /><br />UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE ' . $ident . ' = \''. $dataobject->$ident .'\'');
            }
            if (!empty($CFG->dblogerror)) {
                $debug = debug_backtrace();
                foreach ($debug as $d) {
                    if (strpos($d['file'],'datalib') === false) {
                        error_log("SQL ".$db->ErrorMsg()." in {$d['file']} on line {$d['line']}. STATEMENT:  UPDATE $CFG->prefix $table SET $update WHERE $ident = '{$dataobject->$ident}'");
                        break;
                    }
                }
            }
            return false;
        }
    }

}

?>
